from fastapi import FastAPI,Depends,HTTPException, status

from fastapi.middleware.cors import CORSMiddleware#跨域请求

from my_fake_db_connect import fake_db_connect#虚拟数据库连接

from my_models import Token,TokenData,User,UserInDB#引入数据模型

from my_tools import PasswordCheck,TokenCreator

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")#初始化安全性方案对象

#初始化工具类
tokencreator=TokenCreator()
passwordcheck=PasswordCheck('fake_data.json')
db=fake_db_connect('fake_data.json')

# 放行跨域请求的域名

origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    "http://localhost:8080",
    "http://localhost:8848",
    "http://127.0.0.1:8848",
    "http://127.0.0.1:5500"
]

app=FastAPI()

# 添加跨域方案
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)



#游客的访问
@app.get("/hello")
async def hello(name:str):
    return "hello,"+name+"!"

#登录，返回令牌
@app.post("/token", response_model=Token)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    '''
    处理登录请求
    '''
    #user = authenticate_user(
    #    fake_users_db, form_data.username, form_data.password)
    username=form_data.username
    password=form_data.password

    if not passwordcheck.check(username, password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )

    access_token=tokencreator.create(username)
    print('返回用户令牌',access_token)
    # 返回用户令牌
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/user/me", response_model=User)
async def get_current_user(token: str = Depends(oauth2_scheme)):
    '''
    获取当前用户信息。
    '''
    # 默认错误信息
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    # 尝试解码token获取username
    
    username=tokencreator.decode(token)
    
    if username is None:
        print('此处出错1')
        raise credentials_exception
        

    try: 
        userinfo=db.get(username)
    except:
        print('此处出错2')
        raise credentials_exception
        
    if userinfo is None:
        print('此处出错3')
        raise credentials_exception
    return userinfo
    